import React, { PropTypes, Component } from 'react';
import Table from './MyTable'
import Column from './Column'
import { myAjax, getAuthShop, ROOTURL_TABLE } from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

export default React.createClass({
  getInitialState: function() {
    let date = new Date();
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      tData: [{}],
      shopsForAdm: [],
      areaArray: [],
      shopNameArray: [],
      processData: [{}],
      areaSelect: '请选择地区',
      shopSelect: '请选择门店',
    };
  },
  componentWillMount: function() {
    let _this = this;
  },
  componentDidMount: function() {
    let _this = this;
    this.getData();
  },
  getData: function() {
    let _this = this;
    console.log('执行getData');
    myAjax(ROOTURL_TABLE + 'cafune/servant/sermondailydata.api', 'POST', {year:this.state.year, month:this.state.month}, function(data) {
      _this.setState({
        processData: data,
      }, () => {
        getAuthShop(null, function(data) {
          _this.setState({
            shopsForAdm: data,
          }, () => {
            // 处理数据格式为[{}]
            let _processData = [];
            let ids = _this.state.processData.servantIds;

            for(var i in ids) {
              let id = ids[i];
              _processData.push(_this.state.processData[id]);
            }
            let processData = [];
            for(let i in _processData) {
              let a = {'servantName': _processData[i].servantName, 'servantShop': _processData[i].servantShop, 'servantShopLoc': _processData[i].servantShopLoc};
              let b = _processData[i].dailyServeCount;
              Object.assign(a, b);
              processData.push(a);
            }
            // 获取权限列表数组(有重复数据)
            let shopsForAdm = [];
            _this.state.shopsForAdm.forEach((shopMes) => {
              shopsForAdm.push(shopMes.dname);
            }); 
            // 过滤获取有权限数据与权限列表去重
            let areaArray = new Set();
            let shopNameArray = new Set();
            let permissionData = processData.filter((data) => {
              if(shopsForAdm.indexOf(data.servantShop) === -1) {
                return false
              } else {
                areaArray.add(data.servantShopLoc);
                shopNameArray.add(data.servantShop)
                return true 
              }
            });
            // 设置相应state，并回调执行地区筛选
            _this.setState({
              processData: permissionData,
              areaArray: Array.from(areaArray),
              shopNameArray: Array.from(shopNameArray),
            }, () => {
              _this.filterData();
            });
          });
        });
      });
    }, function(error) {});
  },
  changeArea: function(e) {
    let _this = this;
    let areaSelect = e.target.value;
    this.setState({
      areaSelect: areaSelect,
      shopSelect: '请选择门店',
    }, () => {
      _this.filterData();
    });
  },
  changeShop: function(e) {
    let _this = this;
    let shopSelect = e.target.value;
    this.setState({
      shopSelect: shopSelect,
    }, () => {
      _this.filterData();
    });
  },
  handleClick: function() {   
    let _this = this;

    let yearSelect = parseInt(this.state.year);
    let monthSelect = parseInt(this.state.month);
    if(!yearSelect || !(/^2\d{3}$/.test(yearSelect))) {
      alert("内容不能为空或格式错误");
      return
    }
    if(!monthSelect || !(/^0?[1-9]{1}$|1[0-2]/.test(monthSelect))) {
      alert("内容不能为空或格式错误");
      return
    }
    this.setState({
      year: yearSelect,
      month: monthSelect,
    }, _this.getData());
  },
  filterData: function() {// 按地区筛选数据
    console.log('执行filterData');
    let _this = this;
    let areaSelect = this.state.areaSelect;
    let shopSelect = this.state.shopSelect;
    let selectData = this.state.processData.filter((data) => {
      if(shopSelect == '请选择门店') {
        return areaSelect == '请选择地区'||data.servantShopLoc == areaSelect
      } else {
        return data.servantShop == shopSelect
      }
    });
    this.setState({
      tData: selectData,
    });
  },
  render: function() {
    return (
      <div>
        <div>
          <select value={this.state.areaSelect} onChange={this.changeArea} className={styles['select']}>
            <option value="请选择地区">请选择地区</option>
            {
              !this.state.areaArray[0]||this.state.areaArray.map((area) => {
                return (
                  <option value={area} key={area}>{area}</option>
                );
              })
            }
          </select>
          <select value={this.state.shopSelect} onChange={this.changeShop} className={styles['select']}>
            <option value="请选择门店">请选择门店</option>
            {
              !this.state.shopNameArray[0]||this.state.shopNameArray.map((name, index) => {
                return (
                  <option key={name} value={name}>{name}</option>
                );
              })
            }
          </select>
          <label>
            <input onChange={(e)=>{this.setState({year: e.target.value})}} onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：2016" />年
            <span>&nbsp;&nbsp;</span><input onChange={(e)=>{this.setState({month: e.target.value})}} onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：3" />月
          </label>
          <button type="button" onClick={this.handleClick} onKeyPress={this.handleKeyPress} className={styles.button}>确定</button>
        </div>
        <div>
        <Table data={this.state.tData} className={styles.container}>
          <Column dataKey='servantName' name='理发师' width="120px" order="false" key={`col-servantName`}/>
          <Column dataKey='servantShop' name='所属门店' width="120px" order="false" key={`col-servantShop`}/>
          <Column dataKey='servantShopLoc' name='地区' width="120px" order="false" key={`col-servantShopLoc`}/>
          { 
            !this.state.tData[0]||Object.keys(this.state.tData[0]).map(entry => {
              if(/\d/.test(entry)) {
                return <Column dataKey={entry} name={entry} key={`col-${entry}`}/>
              }              
            })
          }
        </Table>
        </div>
      </div>
    );
  }
});
